/*
 * Created on 07.10.2005
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package de.fmannan.addbook.editor.util;

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;

import de.fmannan.addbook.editor.types.TypesUtil;


public class LongUtil {

    private static final NumberFormat standardFormat = NumberFormat.getInstance();
    private static final String INVALID_STRING_DISPLAY = "";

    private LongUtil() {
        // Util is not instantiable.
    }

    public static String formatLong(long value)
    {
        return TypesUtil.isValidLong(value) ? standardFormat.format(value) : INVALID_STRING_DISPLAY;
    }

    public static long parseLong(String numberString) throws ParseException 
    {        
        String trimmedString = numberString.trim();        
        return (trimmedString != null && ! trimmedString.equals(INVALID_STRING_DISPLAY)) ? parseIntegerOnly(trimmedString) : TypesUtil.getInvalidLong();
    }

    private static long parseIntegerOnly(String trimmedString) throws ParseException {
        // Accept integer values only. Raise exception if necessary.
        // TODO: This looks somewhat clumsy. Is there a better way to achieve the same effect?
        standardFormat.setParseIntegerOnly(true);
        ParsePosition position = new ParsePosition(0);
        Number parsedNumber = standardFormat.parse(trimmedString, position);
        int firstUnusedPosition = position.getIndex();
        if ( firstUnusedPosition != trimmedString.length() ) {
            throw new ParseException("Bitte geben Sie eine ganze Zahl, d.h. eine Zahl ohne Kommastellen ein!", firstUnusedPosition);
        }
        
        return parsedNumber.longValue();
    }

    
    public static String formatXMLLong(long value)
    {
        return TypesUtil.isValidLong(value) ? Long.toString(value) : INVALID_STRING_DISPLAY;
    }

    public static long parseXMLLong(String numberString) throws ParseException 
    {        
    	return (numberString != null && !numberString.equals(INVALID_STRING_DISPLAY)) ? Long.parseLong(numberString) : TypesUtil.getInvalidLong();
    }

}
